# -*- coding:utf-8 -*-

## ========================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## ========================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iArea import SearchAreaGUI
from iNotes import NotesGUI

class PersonGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.balloon=balloon
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Personne")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgNotes=PhotoImage(file="img/edit.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.listObject=[City]
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Person-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Person-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tPersonGUI\tStart")
		self.makePerson()

	# DEBUT de la gestion du module Person  ------------------------------------------------------------------------------------------------------------
	def clearFieldPerson(self):
		for value in self.personValues:
			value.set("")
		self.statusPersonCB.selectitem(1)
		self.personValues[2].set("MO")
		self.listObject=[City]

	def selectPerson(self, event):
		result = Person.select(Person.q.id==self.idListPerson[int(self.listPerson.curselection()[0])])
		for row in result:
			self.selectedPerson = row
		if self.selectedPerson.fname != None:self.personValues[0].set(self.selectedPerson.fname)
		self.personValues[1].set(self.selectedPerson.lname)
		self.personValues[2].set(self.selectedPerson.status)
		self.personValues[3].set(self.selectedPerson.address1)
		if self.selectedPerson.address2 != None:self.personValues[4].set(self.selectedPerson.address2)
		if self.selectedPerson.tel != None:self.personValues[10].set(self.selectedPerson.tel)
		if self.selectedPerson.fax != None:self.personValues[11].set(self.selectedPerson.fax)
		if self.selectedPerson.cell != None:self.personValues[12].set(self.selectedPerson.cell)
		if self.selectedPerson.email != None:self.personValues[13].set(self.selectedPerson.email)
		if self.selectedPerson.comment != None:self.personValues[14].set(self.selectedPerson.comment)
		self.listObject[0] = self.selectedPerson.city
		self.personValues[5].set(self.listObject[0].name)
		self.personValues[6].set(self.listObject[0].zipCode.code)
		self.personValues[7].set(self.listObject[0].zipCode.county.name)
		self.personValues[8].set(self.listObject[0].zipCode.county.state.name)
		self.personValues[9].set(self.listObject[0].zipCode.county.state.country.name)
		# Affichage du Status dans la ComboBox
		status = ( (u"CP", 0), (u"MO", 1), (u"MA", 2), (u"MD", 3), )
		for n in status:
			if n[0] == self.selectedPerson .status: self.statusPersonCB.selectitem(n[1])
		# activation du bouton supprimer
		self.deletePersonBt.config(state=NORMAL)

	def searchPerson(self, event=None):
		if self.searchPersonValue.get() != "":
			self.listPerson.delete(0,END)
			self.idListPerson = []
			result = Person.select(Person.q.lname.startswith(self.searchPersonValue.get().encode("utf-8")), orderBy=Person.q.lname)
			for row in result:
				self.listPerson.insert(END, row.lname+" - "+row.fname)
				self.idListPerson.append(row.id)
		else:
			self.listPerson.delete(0,END)
			self.idListPerson = []
			result = Person.select(orderBy=Person.q.lname)
			for row in result:
				self.listPerson.insert(END, row.lname+" - "+row.fname)
				self.idListPerson.append(row.id)

	def makePerson(self):
		leftFrame = Frame(self)
		# Fiche Person  (présentation colonne de gauche)
		Label(leftFrame, text=u"Personne").pack()
		# Création des champs a renseigner pour un object Person
		personLabels = (u"Prénom", u"Nom", u"Status", u"Adresse", u"Adresse", u"Ville", u"Code postal", u"Département", u"Région", u"Pays", u"Tél", u"Fax", u"Mobile", u"Email", u"Notes")
		self.personValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		statusCB = (u"Company", u"Monsieur", u"Madame", u"Mademoiselle")
		count = 0
		for name in personLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 2: # Status
				self.statusPersonCB=Pmw.ComboBox(f, selectioncommand=self.personStatus, scrolledlist_items=statusCB, listheight=100)
				self.statusPersonCB._entryfield._entryFieldEntry.config( width = 25)
				self.statusPersonCB.pack(side=LEFT, fill=X)
				self.statusPersonCB.selectitem(1)
				self.personValues[2].set("MO")
			elif count==5:
				Entry(f, textvariable=self.personValues[count], width=25 , state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				selectAreaBT=Button(f, image=self.imgSearch, command=self.ctrlArea)
				selectAreaBT.pack(side=RIGHT)
				self.balloon.bind(selectAreaBT, u"Séléctionner un lieu")
			elif count > 5 and count < 10: 
				Entry(f, textvariable=self.personValues[count], state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			elif count == 14: # Notes
				Entry(f, textvariable=self.personValues[count], width=25).pack(side=LEFT, fill=X)
				myNotes=Button(f, image=self.imgNotes, command=lambda x=self.personValues[count]:self.ctrlNotes(x,u"Notes"), padx=4, pady=1)
				myNotes.pack(side=RIGHT)
				self.balloon.bind(myNotes, u"Détails de la note")
			else: 
				Entry(f, textvariable=self.personValues[count], width=28).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.savePersonBt=Button(s, image=self.imgSave, command=self.createPerson)
		self.savePersonBt.bind("<Return>", self.createPerson)
		self.savePersonBt.pack(side=LEFT)
		self.balloon.bind(self.savePersonBt, u"Enregistrer")
		self.deletePersonBt=Button(s, image=self.imgDelete, command=self.deletePerson, state=DISABLED)
		self.deletePersonBt.bind("<Return>", self.deletePerson)
		self.deletePersonBt.pack(side=LEFT)
		self.balloon.bind(self.deletePersonBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Liste des Personnes existantes (présentation colonne de droite)
		rightFrame = Frame(self) 
		Label(rightFrame, text=u"Liste des Personnes").pack(side=TOP, fill=X)
		self.searchPersonValue = StringVar()
		self.searchPersonEt = Entry(rightFrame,  width=43, textvariable=self.searchPersonValue, relief=GROOVE)
		self.searchPersonEt.bind("<KeyRelease>", self.searchPerson)
		self.searchPersonEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchPersonEt, u"Saisir les premières lettres d'une personne\npour une recherche plus précise,\nla liste est classée par Nom.")
		s = Frame(rightFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listPerson = Listbox(s)
		self.listPerson.config(yscrollcommand=scrollbar.set,width=40, selectmode=SINGLE, height=18)
		self.listPerson.bind("<ButtonRelease-1>",self.selectPerson)
		scrollbar.config(command=self.listPerson.yview)
		self.listPerson.pack()
		self.balloon.bind(self.listPerson, u"Séléctionner une personne\npour la visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		rightFrame.pack(side=RIGHT, fill=BOTH)
		self.searchPerson()

	def ctrlArea(self):
		SearchAreaGUI(balloon=self.balloon, index=0, listObject=self.listObject, fieldCity=self.personValues[5], fieldZipCode=self.personValues[6], fieldCounty=self.personValues[7], fieldState=self.personValues[8], fieldCountry=self.personValues[9], log=self.log, path=self.path)

	def ctrlNotes(self,field,title):
		NotesGUI(field=field,title=title, log=self.log, path=self.path)

	def personStatus(self, value):
		status = ( (u"CP", u"Company"), (u"MO", u"Monsieur"), (u"MA", u"Madame"), (u"MD", u"Mademoiselle"), ) 
		for n in status:
			if n[1] == value: self.personValues[2].set(n[0])

	def verifyPerson(self):
		if self.personValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Nom est obligatoire !\nMerci de le compléter.")
			return False
		elif self.personValues[2].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Status est obligatoire !\nMerci de le compléter.")
			return False
		elif self.personValues[3].get() == "":
			showerror(u"Erreur de saisie", u"Le premier champ Adresse est obligatoire !\nMerci de le compléter.")
			return False
		elif self.personValues[5].get() == "":
			showerror(u"Erreur de saisie", u"La séléction d'un lieu est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createPerson(self, event=None):
		if self.verifyPerson():
			if  self.deletePersonBt.config()["state"][4] == "normal":
				self.modifyPerson()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouvelle personne ?\n" % self.personValues[1].get()):
					Person(fname=self.personValues[0].get().encode("utf-8"),
						lname=self.personValues[1].get().encode("utf-8"),
						status=self.personValues[2].get().encode("utf-8"),
						address1=self.personValues[3].get().encode("utf-8"),
						address2=self.personValues[4].get().encode("utf-8"),
						city=self.listObject[0],
						tel=self.personValues[10].get().encode("utf-8"),
						fax=self.personValues[11].get().encode("utf-8"),
						cell=self.personValues[12].get().encode("utf-8"),
						email=self.personValues[13].get().encode("utf-8"),
						comment=self.personValues[14].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchPerson()
				self.clearFieldPerson()

	def modifyPerson(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier la Personne %s ?" % self.selectedPerson.lname):
			self.selectedPerson.fname=self.personValues[0].get().encode("utf-8")
			self.selectedPerson.lname=self.personValues[1].get().encode("utf-8")
			self.selectedPerson.status=self.personValues[2].get().encode("utf-8")
			self.selectedPerson.address1=self.personValues[3].get().encode("utf-8")
			self.selectedPerson.address2=self.personValues[4].get().encode("utf-8")
			self.selectedPerson.city=self.listObject[0]
			self.selectedPerson.tel=self.personValues[10].get().encode("utf-8")
			self.selectedPerson.fax=self.personValues[11].get().encode("utf-8")
			self.selectedPerson.cell=self.personValues[12].get().encode("utf-8")
			self.selectedPerson.email=self.personValues[13].get().encode("utf-8")
			self.selectedPerson.comment=self.personValues[14].get().encode("utf-8")
		self.deletePersonBt.config(state=DISABLED)
		self.clearFieldPerson()

	def deletePerson(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Personne %s ?\nCette opération est irréversible !" % self.selectedPerson.lname):
			Person.delete(self.selectedPerson.id)
			self.searchPerson()
		self.deletePersonBt.config(state=DISABLED)
		self.clearFieldPerson()
	# FIN de la gestion du module Person -----------------------------------------------------------------------------------------------------------------

class PersonListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des personnes")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		## # Afficher un icon personnalisé
		## try:
			## if os.name =="posix":
				## img = PhotoImage(file=self.path+"/icons/Parking-icon.gif")
				## self.tk.call("wm", "iconphoto", self._w, img)
			## else:
				## self.iconbitmap(default=self.path+"/icons/Parking-icon.gif")
		## except TclError:
			## self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		## self.log.info("\tPersonListGUI\tStart")
		self.makeListPerson()

	def selectListPerson(self, event):
		if self.listListPerson.get(0)!="":
			result = Person.select(Person.q.id==self.idListListPerson[int(self.listListPerson.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row .fname+" - "+row .lname)
				self.destroy()

	def searchListPerson(self, event=None):
		if self.searchListPersonValue.get() != "":
			self.listListPerson.delete(0,END)
			self.idListListPerson = []
			result = Person.select(Person.q.lname.startswith(self.searchListPersonValue.get().encode("utf-8")), orderBy=Person.q.lname)
			for row in result:
				self.listListPerson.insert(END, row.fname+" - "+row.lname)
				self.idListListPerson.append(row.id)
		else:
			self.listListPerson.delete(0,END)
			self.idListListPerson = []
			result = Person.select(orderBy=Person.q.lname)
			for row in result:
				self.listListPerson.insert(END, row.fname+" - "+row.lname)
				self.idListListPerson.append(row.id)

	def makeListPerson(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Personnes").pack(side=TOP, fill=X)
		self.searchListPersonValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListPersonEt = Entry(s,  width=32, textvariable=self.searchListPersonValue, relief=GROOVE)
		self.searchListPersonEt.bind("<KeyRelease>", self.searchListPerson)
		self.searchListPersonEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListPersonEt, u"Saisir les premiéres lettres d'une Personne\npour une recherche plus précise,\nla liste est classée par Nom.")
		newPersonBt=Button(s, image=self.imgNew, command=self.ctrlPerson)
		newPersonBt.pack(side=RIGHT)
		self.balloon.bind(newPersonBt, u"Créer une nouvelle Personne")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListPerson = Listbox(s)
		self.listListPerson.config(yscrollcommand=scrollbar.set,width=33, selectmode=SINGLE, height=16)
		self.listListPerson.bind("<ButtonRelease-1>",self.selectListPerson)
		scrollbar.config(command=self.listListPerson.yview)
		self.listListPerson.pack()
		self.balloon.bind(self.listListPerson, u"Séléctionner une personne.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListPerson()

	def ctrlPerson(self):
		PersonGUI(balloon=self.balloon, log=self.log, path=self.path)